<template>
  <div class="form-container">
    <el-form 
      :model="formData" 
      :rules="rules" 
      ref="formRef" 
      label-width="100px" 
      class="demo-ruleForm"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" />
      </el-form-item>
      
      <el-form-item label="密码" prop="password">
        <el-input v-model="formData.password" type="password" show-password />
      </el-form-item>
      
      <el-form-item label="姓名" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>
      
      <el-form-item label="性别">
        <el-radio-group v-model="formData.gender">
          <el-radio label="男">男</el-radio>
          <el-radio label="女">女</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="联系电话" prop="telephone">
        <el-input v-model.number="formData.telephone" />
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="submitForm">立即创建</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import dormitoryAdminApi from '@/api/dormitoryAdmin'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const formRef = ref(null)

const formData = ref({
  username: '',
  password: '',
  name: '',
  gender: '男',
  telephone: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  telephone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()
    const res = await dormitoryAdminApi.saveDormitoryAdmin(formData.value)
    
    if (res.data.code === 0) {
      await ElMessageBox.alert(`${formData.value.username}添加成功`, {
        confirmButtonText: '确定',
        callback: () => {
          router.push('/dormitoryAdminManager')
        }
      })
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('提交失败: ' + (error.response?.data?.message || error.message))
    }
  }
}

// 重置表单
const resetForm = () => {
  formRef.value.resetFields()
}
</script>

<style scoped>
.form-container {
  margin: 60px auto;
  width: 500px;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.demo-ruleForm {
  margin-top: 20px;
}

.el-radio-group {
  width: 100%;
}
</style>